<template>
  <el-header style="background-color: lightgray; text-align: right; font-size: 12px;height: 100px;">
    <h1 style="font-size: 30px; text-align: left;">检查录入</h1>
  </el-header>
      
  <h3>患者搜索</h3>
          <el-row>
            <el-col :span="4"><div class="grid-content ep-bg-purple-light" />
      <el-form-item label="病历号：" prop="patientName"  class="label">
     <el-input v-model="form.orderNo" placeholder="请输入病历号"/>
   </el-form-item>
  </el-col>
  <el-col :span="6"><div class="grid-content ep-bg-purple-light" /> 
      <el-form-item label="姓名：" prop="patientName"  class="label">
     <el-input v-model="form.patientName" placeholder="请输入"  />
   </el-form-item>
  </el-col>
  <el-col :span="6">
      <el-button type="primary" @click="search">搜索</el-button>
      <el-button type="primary" @click="storageCheck">暂存</el-button>
    
      <el-button type="danger" @click="resetForm">重置</el-button>
  </el-col>
</el-row>
<h3>患者信息</h3>
  <el-row>
      <el-col :span="4">
      <el-form-item label="姓名：" prop="fangStatus" class="label" >
     <el-input v-model="form.patientName1"   disabled/>   
     </el-form-item>
     </el-col>
      <el-col :span="6">
        <el-form-item label="身份证号：" prop="identityNo" class="label" >
          <el-input v-model="form.identityNo"   disabled/>
        </el-form-item> 
  </el-col>
  <el-col :span="6">
     <el-form-item label="性别：" prop="fangStatus" class="label" >
       <el-input v-model="form.gender" disabled/>
     </el-form-item>
  </el-col>
  <el-col :span="6">
    <el-form-item label="年龄：" prop="age" class="label" >
      <el-input v-model="form.age" placeholder="age" label="年龄" disabled/>   
    </el-form-item>
  </el-col>
  </el-row>
  <div class="box" style="background-color: white;width: 800px;height: auto;margin: 20px;">
    <el-row :gutter="20">
      <el-tag type="primary" style="margin-left: 20px;">当前选择的检查项目是: {{ tableData.techName }}</el-tag>
    </el-row>
    
    <el-row :gutter="20">
      <el-col :span="6"><div class="grid-content ep-bg-purple"><h3 style="color: black;">编号：{{ tableData.registerId }}</h3></div></el-col>
    </el-row>
    
    <el-row :gutter="20">
      <el-col :span="4"><div class="grid-content ep-bg-purple">姓名：{{ tableData.patientName }}</div></el-col>
      <el-col :span="4"><div class="grid-content ep-bg-purple">性别：{{ tableData.patientGender }}</div></el-col>
      <el-col :span="4"><div class="grid-content ep-bg-purple">年龄：{{ tableData.patientAge }}</div></el-col>
      <el-col :span="4"><div class="grid-content ep-bg-purple">医生姓名：{{ tableData.doctorName }}</div></el-col>
      <el-col :span="4"><div class="grid-content ep-bg-purple">医生ID：{{ tableData.doctorId }}</div></el-col>
    </el-row>
    
    <el-row :gutter="20">
      <el-col :span="4"><div class="grid-content ep-bg-purple">检查编码：{{ tableData.techCode }}</div></el-col>
      <el-col :span="4"><div class="grid-content ep-bg-purple">检查规格：{{ tableData.techFormat }}</div></el-col>
      <el-col :span="4"><div class="grid-content ep-bg-purple">检查费用：￥{{ tableData.techPrice }}</div></el-col>
      <el-col :span="4"><div class="grid-content ep-bg-purple">费用分类：{{ tableData.priceType }}</div></el-col>
      <el-col :span="4"><div class="grid-content ep-bg-purple">状态：{{ tableData.checkState }}</div></el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="12"><div class="grid-content ep-bg-purple">创建时间：{{ tableData.creationTime }}</div></el-col>
    </el-row>
  </div>

  <el-button style="margin: 20px;" type="primary">重置医生</el-button>
  <el-select v-model="form.deptId" style="width: 200px;margin: 20px;" @click="selectCheckDept()" placeholder="请选择科室">
      <el-option v-for="item in deptList" :key="item.deptId" :label="item.deptName" :value="item.deptId"></el-option>
  </el-select>
  <el-select v-model="form.inputCheckEmployeeId" style="width: 200px;margin: 20px;" @click="selectDoctor()" placeholder="请选择医生">
      <el-option v-for="item in doctors" :key="item.id" :label="item.realName" :value="item.id"></el-option>
  </el-select>

  <div class="input" style="margin:20px;">
    检查内容：
    <el-input placeholder="请输入检查结果" v-model="form.checkResult" style="width: 700px;height: 100px;margin-left: 20px;"></el-input>
  </div>

  <el-button style="margin: 20px;" @click="submitCheckRequestResult()" type="primary">提交检查结果</el-button>
  <el-button @click="clearInput()" type="primary">重置检查结果输入</el-button>
  <el-button style="margin: 50px;width: 200px;" type="success">打印结果</el-button>
</template>

<script lang="ts" setup name="CheckNormal">
import axiosInstance from '@/utils/axiosUtils';
import { ref, reactive } from 'vue';
import { useRoute } from 'vue-router';
import { ElMessageBox } from 'element-plus';
import router from '@/router';
const route = useRoute();
const patientCheckData = JSON.parse(sessionStorage.getItem('PatientCheckNormal')) || {};
//各个项目的医生列表
const doctors=ref([
  {
   id:0,
   realName: '',
  }
]);
const deptList=ref([]);
const form = reactive({
  registerId: patientCheckData.registerId || null,
  orderNo: patientCheckData.orderNo || null,
  patientName: patientCheckData.patientName || route.query.patientName || '',
  identityNo: patientCheckData.identityNo || '',
  gender: patientCheckData.gender || '',
  age: patientCheckData.age || '',
  checkStatus: 1,
  patientName1: patientCheckData.patientName || '',
  deptId: patientCheckData.deptId || '',
  inputCheckEmployeeId: patientCheckData.inputCheckEmployeeId || '',
  checkResult: '',
});
// tableData将存放从后端获取的检查项数据
const tableData = ref({
  registerId: '',
  patientName:   '',
  patientAge:   '',
  patientGender:   '',
  doctorName:   '',
  doctorId: '',
  medicalTechnologyId: '',
  techCode:   '',
  techName:   '',
  techFormat:   '',
  techPrice: '',
  priceType:   '',
  creationTime:   '',
  checkState:   '',
}); // 初始化为一个空对象
//暂存检查项目
const storageCheck=()=>{
  sessionStorage.setItem('PatientCheckNormal',JSON.stringify(form))
   
}
//清空表单函数
const resetForm=()=>{
for(const key in form){
  form[key]='';
}
};
//清空表单输入项
const clearInput = () => {
  form.checkResult = '';
};
// 搜索检查项目信息
const selectPatientCheckByTwo = (registerId, medicalTechnologyId) => {
  axiosInstance.get('/api/checkRequest/selectPatientCheckByTwo', {
    params: {
      registerId: registerId,
      medicalTechnologyId: medicalTechnologyId
    }
  })
  .then(response => {
    console.log('响应数据:', response.data);
    tableData.value = response.data; // 假设响应是单个对象
  })
  .catch(error => {
    console.error('查询出现错误:', error);
  });
};
//获取检查科室列表
const selectCheckDept = () => {
  axiosInstance.get('/api/department/selectCheckDeptNameAndId').then(res => {
    console.log(res.data)
   
// 清空之前的 deptList，以防重复推入
deptList.value = [];  // 保证这里是清空 deptList.value，而不是 deptList
   res.data.forEach((item: { dept_name: any; id: any; dept_ode: any; dept_type: any; }) => {
    deptList.value.push({
      deptName: item.dept_name,
      deptId: item.id,
      deptOde: item.dept_ode,
      deptType: item.dept_type,
    })
    })
  }).catch(err => {
    console.log(err)
  })
 }
 //根据科室id获取医生列表
const selectDoctor = () => {
  axiosInstance.get('/api/employee/selectDoctorsById', { params: { deptId: form.deptId } })
    .then(res => {
      console.log('返回的数据:', res.data);
      if (Array.isArray(res.data)) { // 确认返回的数据是数组
        doctors.value = []; // 清空医生列表（可选）
        res.data.forEach(item => {
          doctors.value.push({
            id: item.id,              // 假设 Employee 类中有这些属性
            realName: item.realname,  // 需要确认 Employee 类中有 realName 属性
          });
        });
        console.log('医生列表', doctors.value);
      } else {
        console.error('数据格式错误，期望数组，但实际为:', typeof res.data);
        ElMessageBox.alert('获取数据失败，请重试'); // 提示用户请求失败
      }
    })
    .catch(err => {
      console.log(err);
      ElMessageBox.alert('获取数据失败，请重试,可能是因为您未选择科室'); // 提示用户请求失败
    });
}
// 获取URL中传递的参数
const registerId = route.query.registerId;
const medicalTechnologyId = route.query.medicalTechnologyId;
// 搜索患者个人信息
const search = () => {
  // 确保去除输入值的空格
  const orderNo = form.orderNo ? form.orderNo.trim() : null;
  const realName = form.patientName ? form.patientName.trim() : null;

  // 确保至少提供一个查询参数
  if (!orderNo && !realName) {
    console.error('请提供病历号或真实姓名进行查询');
    return; // 不进行请求
  }

  // 发送请求
  axiosInstance.get('/api/register/selectOrderPatient', {
    params: {
      orderNo: orderNo,
      realName: realName
    }
  })
  .then(response => {
    console.log('响应数据:', response.data);

  //检查数据是否不为空
    if (response.data ) {
      if(!form.orderNo){
        form.orderNo=response.data.caseNumber;
      }else if(!form.patientName){
        form.patientName=response.data.realName;
      }
      form.gender = response.data.gender;
      form.age = response.data.age;
      form.identityNo=response.data.cardNumber;
      form.patientName1=response.data.realName;
      form.registerId=response.data.id;
    } else {
      console.warn('未找到匹配的病人信息');
    }
  })
  .catch(error => {
    console.error('查询出现错误:', error);
  });

};
// 调用函数获取数据
search();
selectPatientCheckByTwo(registerId, medicalTechnologyId);
const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

//提交检查结果
const submitCheckRequestResult = () => {
  // 发送请求
  axiosInstance.post('/api/checkRequest/submitCheckRequestResult', {
    registerId: form.registerId,
    medicalTechnologyId: medicalTechnologyId,
    checkResult: form.checkResult,
    checkTime:formatDate(new Date()),
    inputCheckEmployeeId: form.inputCheckEmployeeId,
  })
  .then(response => {
    console.log('提交检查结果成功:', response.data);
    ElMessageBox.alert('提交检查结果成功'); // 提示用户提交成功
  })
  .catch(error => {
    console.error('提交检查结果失败:', error);
    ElMessageBox.alert('提交检查结果失败，请重试'); // 提示用户提交失败
  });
  // 重置表单
  resetForm();
};
</script>

<style lang="css" link-ref="main.css"/>
<style scoped> 
  h1 {
    padding-left: 30px;
  }
  .label {
    display: inline-block;
    width: 200px;
    color: grey;
    padding-left: 30px;
  }
  .grid-content {
    margin-left: 20px;
  }
  .el-row:last-child {
    margin-left: 20px;
  }
  .el-col {
    border-radius: 4px;
  }
  .grid-content {
    border-radius: 4px;
    color: grey;
  }
  h3 {
    padding-left: 20px;
  }
</style>
